package com.sneakxy.cloudbase.platform.config;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import com.alibaba.cloud.seata.feign.CloudBaseSeataFeignClient;
import com.alibaba.cloud.sentinel.feign.SentinelFeign;
import com.sneakxy.cloudbase.platform.seata.CloudBaseSeataBeanPostProcessor;
import com.sneakxy.cloudbase.platform.seata.CloudBaseSeataContextBeanPostProcessor;
import com.sneakxy.cloudbase.platform.seata.CloudBaseSeataFeignObjectWrapper;

import feign.Client;
import feign.Feign;
import feign.Retryer;

/**
 * 解决seata与高版本spring cloud不兼容问题
 * @author 潜行的虚影
 *
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Client.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class CloudBaseSeataFeignClientAutoConfiguration {

	@Bean
	@Scope("prototype")
	@ConditionalOnClass(name = "com.alibaba.csp.sentinel.SphU")
	@ConditionalOnProperty(name = "feign.sentinel.enabled", havingValue = "true")
	Feign.Builder feignSentinelBuilder(BeanFactory beanFactory) {
		return SentinelFeign.builder().retryer(Retryer.NEVER_RETRY)
				.client(new CloudBaseSeataFeignClient(beanFactory));
	}

	@Bean
	@ConditionalOnMissingBean
	@Scope("prototype")
	Feign.Builder feignBuilder(BeanFactory beanFactory) {
		return Feign.builder().client(new CloudBaseSeataFeignClient(beanFactory));
	}
	
	@Configuration(proxyBeanMethods = false)
	protected static class FeignBeanPostProcessorConfiguration {

		@Bean
		CloudBaseSeataBeanPostProcessor seataBeanPostProcessor(
				CloudBaseSeataFeignObjectWrapper seataFeignObjectWrapper) {
			return new CloudBaseSeataBeanPostProcessor(seataFeignObjectWrapper);
		}

		@Bean
		CloudBaseSeataContextBeanPostProcessor seataContextBeanPostProcessor(
				BeanFactory beanFactory) {
			return new CloudBaseSeataContextBeanPostProcessor(beanFactory);
		}

		@Bean
		CloudBaseSeataFeignObjectWrapper seataFeignObjectWrapper(BeanFactory beanFactory) {
			return new CloudBaseSeataFeignObjectWrapper(beanFactory);
		}

	}
	
}
